<template>
  <el-dialog v-model="visible" :title="title" width="500px" destroy-on-close @close="emit('close')">
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
      <el-form-item label="所属模块" prop="FModuleId">
        <el-select v-model="formData.FModuleId" placeholder="请选择模块" filterable clearable style="width: 100%">
          <el-option v-for="module in moduleList" :key="module.FId" :label="module.FName" :value="module.FId" />
        </el-select>
      </el-form-item>
      <el-form-item label="权限名称" prop="FName">
        <el-input v-model="formData.FName" placeholder="请输入权限名称" />
      </el-form-item>
      <el-form-item label="权限编码" prop="FCode">
        <el-input v-model="formData.FCode" placeholder="请输入权限编码" />
      </el-form-item>
      <el-form-item label="描述" prop="FDescription">
        <el-input v-model="formData.FDescription" type="textarea" placeholder="请输入描述" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { createPermission, updatePermission, getPermissionModules } from "@/api/modules/permission";

// 定义父组件事件
const emit = defineEmits(["close"]);

const visible = ref(false);
const formRef = ref<FormInstance>();
const title = ref("新增权限");
const moduleList = ref<any[]>([]);

const formData = reactive({
  FId: "",
  FName: "",
  FCode: "",
  FDescription: "",
  FModuleId: ""
});

const rules = reactive<FormRules>({
  FModuleId: [{ required: true, message: "请选择所属模块", trigger: "change" }],
  FName: [{ required: true, message: "请输入权限名称", trigger: "blur" }],
  FCode: [{ required: true, message: "请输入权限编码", trigger: "blur" }]
});

// 加载模块列表
const loadModules = async () => {
  const { data } = await getPermissionModules();
  moduleList.value = data;
};

// 这里保留 onMounted，正常弹窗挂载时加载一次即可
onMounted(() => {
  loadModules();
});

const open = (row?: any, FModuleId?: string) => {
  title.value = row?.FId ? "编辑权限" : "新增权限";
  if (row?.FId) {
    Object.assign(formData, row);
  } else {
    resetForm();
    if (FModuleId) {
      formData.FModuleId = FModuleId;
    }
  }
  visible.value = true;
};

const resetForm = () => {
  formData.FId = "";
  formData.FName = "";
  formData.FCode = "";
  formData.FDescription = "";
  formData.FModuleId = "";
};

const handleSubmit = async () => {
  try {
    await formRef.value?.validate();
    if (formData.FId) {
      await updatePermission(formData.FId, formData);
      ElMessage.success("更新成功");
    } else {
      await createPermission(formData);
      ElMessage.success("创建成功");
    }
    visible.value = false;
  } catch {
    // 验证失败不处理
  }
};

defineExpose({ open });
</script>
